package com.lsc.record.core.order;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.lsc.record.config.RecordConfig;
import com.lsc.record.core.entity.TableEntity;
import com.lsc.record.core.service.TableQueryServcie;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;

import lombok.extern.slf4j.Slf4j;

@Component
@Order(-1)
@Slf4j
public class SQLFileCheckOrder implements ApplicationRunner {
	@Resource
	private TableQueryServcie tableService;
	
	@Resource
	private RecordConfig rconfig;

	@Override
	public void run(ApplicationArguments args) throws Exception {
//		log.info("**********初始DATABASE检查-开始**************");
//		List<TableEntity> list = tableService.list(false);
//		if (list == null || list.size() < 1) {
//			log.info("未初始过数据库");
//			initdb();
//		}
//		
//		checkScriptFile();
//		log.info("**********初始DATABASE检查-结束**************");
	}

	private void checkScriptFile() {
		
		
	}

	private void initdb() {
		String ddlHistorySql = "CREATE TABLE DDL_HISTORY(FILENAME VARCHAR(255) NOT NULL,CREATE_TIME TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP,PRIMARY KEY(FILENAME));";
		Db.updateBySql(ddlHistorySql);
		SqlSession sqlSession = null;
		try {
			FlexGlobalConfig defaultConfig = FlexGlobalConfig.getDefaultConfig();
			SqlSessionFactory sqlSessionFactory = defaultConfig.getSqlSessionFactory();
			InputStream scriptInputStream = Resources.getResourceAsStream("sql/init.sql");
			
			sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
			ScriptRunner runner = new ScriptRunner(sqlSession.getConnection());
			runner.setAutoCommit(false); // 或者根据需要设置为true
			runner.setStopOnError(false); // 或根据需要设置为true，遇到错误时停止执行
			runner.runScript(new InputStreamReader(scriptInputStream));
			sqlSession.commit(); //
			
			Db.insert("DDL_HISTORY", Row.of("filename", "sql/init.sql"));
		} catch (Exception e) {
			if (sqlSession != null) {
				sqlSession.rollback(true);
			}
		}
	}

}
